package ivan.home.com.arquivo;

import ivan.home.com.conta.Conta;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;


public class Arquivo {
	
	static Path path = Paths.get("arquivos/documento.txt");
	static Charset utf8 = StandardCharsets.UTF_8;
	
	
	public static void CriarArquivo(){
		try{
			BufferedWriter criar = Files.newBufferedWriter(path, utf8);
		}catch(IOException e){
			e.printStackTrace();
		}
	}
		
	public static void Salvar(ArrayList <Conta> contas) {
		
		try{
			BufferedWriter gravar = Files.newBufferedWriter(path, utf8, StandardOpenOption.APPEND); 
				for(Conta conta : contas){
					gravar.write(conta.getNome() + ";" + conta.getSaldo() + "\r\n");
				}
			gravar.flush();
			gravar.close();
			
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static void Alterar(ArrayList <Conta> contas){
		try{
			BufferedWriter gravar = Files.newBufferedWriter(path, utf8); 
				for(Conta conta : contas){
					gravar.write(conta.getNome() + ";" + conta.getSaldo() + "\r\n");
				}
			gravar.flush();
			gravar.close();
			
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static ArrayList <Conta> Abrir() throws IOException{
		ArrayList<Conta> contas = new ArrayList<Conta>();
		String linha = null;
		String [] nomes;
		try{
			BufferedReader abrir = Files.newBufferedReader(path, utf8);
			while((linha = abrir.readLine()) != null){
				nomes = linha.split(";");
				contas.add(new Conta(nomes[0], Double.parseDouble(nomes[1])));
			}
		}catch(NoSuchFileException e){
			System.err.println("Arquivo não encontrado!");
		}
		return contas;
	}
	
	public static void DeletarTudo() throws IOException{
		try{
			Files.delete(path);
		}catch(NoSuchFileException e){
			System.err.println("Arquivo não encontrado!");
		}
	}

}
